<script>
export default {
  name: 'SelfUpload',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    action: {
      type: String,
      default: ''
    },
    accept: {
      type: String,
      default: '*'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    },
    maxSize: {
      type: Number,
      default: 2
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  computed: {
    fileList: {
      get() {
        return this.value || []
      },
      set(val) {
        this.$emit('update:value', val)
      }
    },
    type() {
      if (this.accept.includes('image')) {
        return 'picture'
      }
      return 'text'
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.$emit('remove', { file, fileList })
    },
    handlePreview(file) {
      this.$emit('preview', file)
    },
    handleSuccess(response, file, fileList) {
      this.$emit('success', { response, file, fileList })
    },
    handleBeforeUpload(file) {
      // 检查文件数量限制
      if (this.limit && this.fileList.length >= this.limit) {
        this.$message.error(`最多只能上传 ${this.limit} 个文件`)
        return false
      }
      // 检查文件类型，如image/*可以接受image/png、image/jpeg等类型
      if (this.accept && this.accept !== '*') {
        const acceptTypes = this.accept.split(',').map(t => t.trim())
        const isValid = acceptTypes.some(type => {
          if (type.endsWith('/*')) {
            const category = type.replace('/*', '')
            return file.type.startsWith(`${category}/`)
          }
          return file.type === type
        })
        if (!isValid) {
          this.$message.error(`文件类型不支持，请上传 ${this.accept} 格式的文件`)
          return false
        }
      }
      if (this.maxSize) {
        if (file.size / 1024 / 1024 > this.maxSize) {
          this.$message.error(`文件大小不能超过 ${this.maxSize}MB`)
          return false
        }
      }
      this.$emit('beforeUpload', file)
    }
  }
}
</script>

<template>
  <el-upload
    class="upload-demo"
    :action="action"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :file-list="fileList || []"
    :list-type="type"
    :on-success="handleSuccess"
    :before-upload="handleBeforeUpload"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">{{ placeholder }}</div>
    <el-input :value="JSON.stringify(fileList)" style="display: none;" />
  </el-upload>
</template>
